import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 静态路由规则所有人都有
}

const mutations = {
  setToken(state, token) {
    state.token = token // 存仓库
    setToken(token) // 持久化本地存储
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  clearToken(state) {
    state.token = '' // 清除仓库中的 token
    removeToken() // 清除本地存储中的 token
  },
  clearUserInfo(state) {
    state.userInfo = {} // 清除仓库中的用户信息
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  async login({ commit }, obj) {
    // setTimeout(() => {
    //   commit('setToken', 'admin-token')
    // }, 1000)
    const res = await login(obj)
    commit('setToken', res)
  },
  async getUserInfo({ commit }) {
    // setTimeout(() => {
    //   // const res = await getInfo(state.token)
    //   commit('setUserInfo', { name: 'admin' })
    // }, 2000)
    const res = await getUserInfo()
    commit('setUserInfo', res)
    return res // 返回用户信息
  },
  logout({ commit }) {
    commit('clearToken') // 清除 token
    commit('clearUserInfo') // 清除用户信息
    // 清除路由规则 重置路由规则
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
